package com.kaisu.blog.infrastructure.id;

import com.kaisu.blog.common.util.IdUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;
import java.lang.reflect.Field;

import static java.util.Objects.isNull;

/**
 * @author kaisu
 */
public class SnowFlakeIdGenerator implements IdentifierGenerator {
    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        String snowflakeId = IdUtils.generateId();
        try {
            Field idField = object.getClass().getDeclaredField("id");
            idField.setAccessible(true);
            Object value = idField.get(object);
            return isNull(value) ? snowflakeId : (Serializable) value;
        } catch (NoSuchFieldException | IllegalAccessException e) {
            return snowflakeId;
        }
    }
}